<template>
  <div class="container">
    <!-- 导出按钮 -->
    <div class="export-button">
      <el-button type="primary" plain @click="exportTable">导出表格</el-button>
    </div>

    <div class="calendar">
      <el-date-picker
          v-model="selectedDate"
          type="month"
          placeholder="选择年月"
          style="width: 180px"
          @change="handleDateChange"
      ></el-date-picker>
      <div class="month-header">{{ formattedSelectedDate }}</div>
      <div class="day-grid">
        <div
            v-for="day in daysInMonth"
            :key="day"
            class="day"
            :class="{ 'normal': day <= daysInMonth, 'abnormal': attendanceStatus[day] === 'abnormal', 'normal': attendanceStatus[day] === 'normal' }"
            @click="handleAttendanceClick(day)"
            @mouseover="handleAttendanceMouseOver(day)"
            @mouseleave="handleAttendanceMouseLeave"
        >
          {{ day }}
          <el-tooltip
              v-if="attendanceStatus[day] === 'abnormal' && showTooltip === day"
              class="item"
              content="考勤异常"
              placement="bottom"
          >
            <i class="el-icon-circle-check"></i>
          </el-tooltip>
        </div>
      </div>
    </div>

    <div >
      <el-table :data="tableData" stripe border @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column prop="teamsId" label="序号" width="80" align="center" sortable></el-table-column>
        <el-table-column prop="teamsName" label="班组名称" width="80" align="center"></el-table-column>
        <el-table-column prop="contractor" label="承包人"></el-table-column>
        <el-table-column prop="contractorPhone" label="联系方式"></el-table-column>
        <el-table-column prop="teamsNumber" label="班组人数"></el-table-column>
        <el-table-column prop="teamsRemark" label="备注"></el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageNum"
                       :page-sizes="[1, 3, 5, 10]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
                       :total="total">
        </el-pagination>
      </div>
    </div>


    </div>

    <!-- 跳转至班组考勤明细页面的按钮 -->

</template>

<script>
import FileSaver from "file-saver";
import XLSX from "xlsx";


export default {
  name: "LaborCount",
  data() {
    return {
      tableData:[],
      total:0,
      pageNum: 1, // 当前的页码
      pageSize: 10,
      user: JSON.parse(localStorage.getItem('xm-user') || '{}'),
      totalItems: 0,
      selectedDate: new Date(),
      daysInMonth: 31,
      attendanceStatus: {},
      showTooltip: null,
      tooltipTimer: null
    };
  },
  computed: {
    formattedSelectedDate() {
      return `${this.selectedDate.getFullYear()}年${this.selectedDate.getMonth() + 1}月`;
    }
  },
  created() {
    this.$request.get('/teams', {
      params: {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
      }
    }).then(res => {
      this.tableData = res.data.rows;
      this.total = res.data?.total
    });

    this.calculateAttendanceStatus();
    this.load(1);
  },
  methods: {
    handleSizeChange(val) {
      this.pageSize = val

    },
    handleSelectionChange(rows) {
      // 当前选中的所有的行数据
      this.ids = rows.map((v) => v.id);
    },
    calculateAttendanceStatus() {
      const randomAttendance = {};
      for (let i = 1; i <= this.daysInMonth; i++) {
        randomAttendance[i] = Math.random() < 0.8 ? 'normal' : 'abnormal';
      }
      this.attendanceStatus = randomAttendance;
    },
    handleDateChange() {
      this.calculateAttendanceStatus();
    },
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum;
    },
    handleAttendanceClick(day) {
      if (this.attendanceStatus[day] === 'abnormal') {
        // 跳转至班组考勤明细界面
        this.$router.push({ name: 'resourcesApply' });
      }
    },
    goToAttendanceDetail(row) {
      // Implement logic to navigate to attendance detail page
      this.$router.push('/teamAttendance')
    },
    handleAttendanceMouseOver(day) {
      if (this.attendanceStatus[day] === 'abnormal') {
        this.showTooltip = day;
      }
    },
    handleAttendanceMouseLeave() {
      // 添加定时器，3秒后隐藏提示框
      this.tooltipTimer = setTimeout(() => {
        this.showTooltip = null;
      }, 3000);
    },
    exportTable() {
      const data = this.tableData;
      const ws = XLSX.utils.json_to_sheet(data);
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
      const fileName = "table_data.xlsx";
      XLSX.writeFile(wb, fileName);
    }
  },
  beforeDestroy() {
    // 组件销毁时清除定时器
    clearTimeout(this.tooltipTimer);
  },
  load(pageNum) {  // 分页查询
    if (pageNum) this.pageNum = pageNum
    this.$request.get('/teams', {
      params: {
        pageNum: this.pageNum,
        pageSize: this.pageSize,

      }
    }).then(res => {
      this.tableData = res.data.rows;
      this.total = res.data?.total
    })
  },
};
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.export-button {
  margin-bottom: 20px;
}

.calendar {
  margin-bottom: 20px;
}

.month-header {
  text-align: center;
  font-size: 20px;
  margin-bottom: 10px;
}

.day-grid {
  display: grid;
  grid-template-columns: repeat(7, 40px);
  grid-gap: 5px;
}

.day {
  width: 40px;
  height: 40px;
  line-height: 40px;
  text-align: center;
  border: 1px solid #ccc;
  cursor: pointer;
}

.normal {
  background-color: #eee;
}

.abnormal {
  background-color: #ffcccc;
}

.table-container {
  width: 80%;
}

.pagination {
  margin-top: 20px;
}
</style>
